package com.xin.springcloudconsumer.controller;

import com.google.gson.Gson;
import com.xin.springcloudconsumer.dto.PageResult;
import com.xin.springcloudconsumer.dto.UserDTO;
import com.xin.springcloudconsumer.enums.ConsumerEnum;
import com.xin.springcloudconsumer.feign.UserFeign;
import com.xin.springcloudconsumer.form.MyfriendForm;
import com.xin.springcloudconsumer.form.UserForm;
import com.xin.springcloudconsumer.utils.JsonUtil;
import com.xin.springcloudconsumer.utils.ResultVOUtils;
import com.xin.springcloudconsumer.utils.SessionUtils;
import com.xin.springcloudconsumer.vo.ResultPage;
import com.xin.springcloudconsumer.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

@Controller
@RequestMapping("/users")
@Slf4j
public class UserController {
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private Gson gson;
    @Autowired
    private SessionUtils sessionUtils;

    /**
     * 创建用户(openId需要在参数中传递进来)
     *
     * @param userForm
     * @return
     */
    @PostMapping("/create")  //required 是否为必传
    @ResponseBody
    public ResultVO create(UserForm userForm) {
        //TODO 传递参数
        userForm.setPhone("123456");
        userForm.setPassword("1234");
        userForm.setNickname("老王");
        userForm.setDesction("hahaha");
        userForm.setHeadImage("http://wx.qlogo.cn/mmopen/vi_32/86BoU9OPn9nRTWClGGCetYQBcpTpfMzLmZibCPvu6lucVczcL73mooZKxLqWzlZ9qCAMR2cLp6drSYy961tesPw/0");
        ResultVO resultVO = userFeign.create(userForm);
        if (resultVO.getCode() == 0) {
            return ResultVOUtils.success();
        }
        return ResultVOUtils.error(1, ConsumerEnum.CREATE_USER_ERROR.getMessage());
    }

    /**
     * 更新个人信息
     * @param userForm
     * @param bindingResult
     * @param map
     * @return
     */
    @PostMapping("/update")
    public ModelAndView update(@Valid UserForm userForm,
                               BindingResult bindingResult,
                               Map<String, Object> map,
                               HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
            //错误页面
            return new ModelAndView("");
        }
        String token = sessionUtils.getToken(request);
        if (StringUtils.isEmpty(token)){
            map.put("message","请先登录!");
            map.put("returnUrl","/login/loginPassword");
            return new ModelAndView("common/msg_error",map);
        }
        userForm.setId(token);
        ResultVO resultVO = userFeign.update(userForm);
        if (resultVO.getCode() == 0) {
           map.put("message","修改成功!");
           map.put("returnUrl","/users/center");
            return new ModelAndView("common/msg_success",map);
        }
        map.put("message","修改失败!");
        map.put("returnUrl","/users/center");
        return new ModelAndView("common/msg_error",map);
    }

    /**
     * 删除用户
     *
     * @param uid
     * @return
     */
    @GetMapping("/delete")
    public ModelAndView delete(@RequestParam(name = "uid", defaultValue = "") String uid) {
        ResultVO resultVO = userFeign.delete(uid);
        if (resultVO.getCode() == 0) {
            return new ModelAndView("");
        }
        return new ModelAndView("");
    }

    /**
     * 模糊查询
     *
     * @param nickname
     * @param pageable
     * @param map
     * @return
     */
    @GetMapping("/findAllByLikeName")
    public ModelAndView findAllByLikeName(@RequestParam(name = "nickname", defaultValue = "") String nickname,
                                          @PageableDefault(page = 1, size = 10) Pageable pageable,
                                          Map<String, Object> map) {

        ResultPage<UserDTO> dtoResultPage = userFeign.findAllByLikeName(nickname, pageable.getPageNumber(), pageable.getPageSize());
        map.put("pageResult", dtoResultPage);
        return new ModelAndView("list/list");
    }

    /**
     * 根据号码查询
     *
     * @param phone
     * @param map
     * @return
     */
    @GetMapping("/findOneByPhone")
    public ModelAndView findOneByPhone(@RequestParam(name = "phone", defaultValue = "") String phone,
                                       Map<String, Object> map) {
        ResultVO<UserDTO> resultVO = userFeign.findOneByPhone(phone);
        if (resultVO.getCode() == 0) {
            String json = JsonUtil.toJson(resultVO.getData());
            UserDTO userDTO = gson.fromJson(json, UserDTO.class);
            map.put("userDTO", userDTO);
            //TODO 跳转页面
            return new ModelAndView("", map);
        }
        //TODO 查询不到
        return new ModelAndView("");
    }

    /**
     * 登录
     *
     * @param phone
     * @param password
     * @return
     */
    @PostMapping("/login")
    public ModelAndView login(@RequestParam(name = "phone", defaultValue = "") String phone,
                              @RequestParam(name = "password", defaultValue = "") String password,
                              HttpServletRequest request,
                              Map<String, Object> map) {
        log.info("phone:{},password:{}",phone,password);
        ResultVO<UserDTO> resultVO = userFeign.login(phone, password);
        if (resultVO.getCode() == 0) {
            String json = JsonUtil.toJson(resultVO.getData());
            UserDTO userDTO = gson.fromJson(json, UserDTO.class);
            sessionUtils.saveToken(request, userDTO.getId(), userDTO.getHeadImage());
            return new ModelAndView("index/index");
        }
        map.put("returnUrl", "/login/loginPassword");
        map.put("message", "账号密码错误!");
        return new ModelAndView("common/msg_error", map);
    }

    /**
     * 注册
     * @param phone
     * @param password
     * @param map
     * @return
     */
    @PostMapping("/register")
    public ModelAndView register(@RequestParam(name = "phone",defaultValue = "")String phone,
                                 @RequestParam(name = "password",defaultValue = "")String password,
                                 Map<String,Object> map){
        if (StringUtils.isEmpty(phone)||StringUtils.isEmpty(password)){
            map.put("message","手机号和密码不能为空!");
            map.put("returnUrl","/register/register");
            return new ModelAndView("common/msg_error");
        }
        UserForm userForm=new UserForm();
        userForm.setPhone(phone);
        userForm.setPassword(password);
        ResultVO resultVO = userFeign.create(userForm);
        if (resultVO.getCode()==0){
              map.put("message","创建成功!");
              map.put("returnUrl","/login/loginPassword");
              return new ModelAndView("common/msg_success");
        }
        map.put("message","创建失败!");
        map.put("returnUrl","/register/register");
        return new ModelAndView("common/msg_error");
    }
    @GetMapping("/center")
    public ModelAndView joinUserCenter(HttpServletRequest request,
                                       Map<String,Object> map){
        String token = sessionUtils.getToken(request);
        ResultVO resultVO = userFeign.findOne(token);
        if (resultVO.getCode()==0){
            String json = JsonUtil.toJson(resultVO.getData());
            UserDTO userDTO = gson.fromJson(json, UserDTO.class);
            map.put("userDTO",userDTO);
            return new ModelAndView("detial/userInfo",map);
        }
        map.put("message","请先登录!");
        map.put("returnUrl","/login/loginPassword");
        return new ModelAndView("common/msg_error",map);
    }

}
